import { Checkbox, Form, Input, Modal, Tree } from "antd";
import { useCallback, useEffect, useRef, useState } from "react";
import { request } from "../../../Api/api";

const AddRightConfig = ({ open, onOk, onCancel }) => {
  const [addingRightConfig, setAddingRightConfig] = useState({
    name: "",
    explain: "",
    jobIds: [],
    rightIds: [],
  });
  const [key, setKey] = useState(Math.random());
  const [jobTrees, setJobTrees] = useState([]);
  const [jobTreeKeys, setJobTreeKeys] = useState([]);
  const [jobTreeExpandedKeys, setJobTreeExpandedKeys] = useState([]);
  const [rightTrees, setRightTrees] = useState([]);
  const [rightTreeKeys, setRightTreeKeys] = useState([]);
  const [rightTreeExpandedKeys, setRightTreeExpandedKeys] = useState([]);
  const submitBtn = useRef(null);
  // 递归遍历树 callback:(item:当前元素)=>void
  const recursion = useCallback((childrenPropertyName, array, callback) => {
    if (array) {
      array.forEach((item) => {
        recursion(childrenPropertyName, item[childrenPropertyName], callback);
        callback(item);
      });
    }
  }, []);
  const bind = useCallback(async () => {
    const jobRes = await request("/job/tree", {}, "GET");
    if (jobRes.code >= 0) {
      const data = jobRes.data;
      const expandedKeys = [];
      recursion("childrenDeps", data, (item) => {
        item.disabled = true;
        expandedKeys.push(item.id);
        item.childrenDeps = [
          ...item.childrenDeps,
          ...item.childrenJobs.map((job) => ({ ...job, selectable: false })),
        ];
      });
      setJobTreeExpandedKeys(expandedKeys);
      setJobTrees(data);
    }
    const rightRes = await request("/right/tree", {}, "GET");
    if (rightRes.code >= 0) {
      const data = rightRes.data;
      const expandedKeys = [];
      recursion("children", data, (item) => {
        expandedKeys.push(item.id);
        item.selectable = false;
      });
      setRightTreeExpandedKeys(expandedKeys);
      setRightTrees(data);
    }
  }, [recursion]);
  let c = 0;
  useEffect(() => {
    async function fecthData() {
      setKey(c++);
      await bind();
    }
    fecthData();
  }, [bind, c]);
  const checkJobsAll = (e) => {
    const checked = e.target.checked;
    const checkedKeys = [];
    if (checked) {
      recursion("childrenDeps", jobTrees, (item) => {
        if (item.childrenDeps === undefined) {
          checkedKeys.push(item.id);
        }
      });
    }
    setJobTreeKeys(checkedKeys);
  };
  const checkRightsAll = (e) => {
    const checked = e.target.checked;
    const checkedKeys = [];
    if (checked) {
      recursion("children", rightTrees, (item) => {
        checkedKeys.push(item.id);
      });
    }
    setRightTreeKeys(checkedKeys);
  };
  return (
    <Modal
      key={key}
      open={open}
      onOk={() => {
        submitBtn.current.click();
      }}
      destroyOnClose={true}
      onCancel={onCancel}
      okText="添加"
      cancelText="取消"
      width="60%"
    >
      <div style={{ height: "60vh", overflow: "auto" }}>
        <div>
          <Form
            onFinish={() => {
              onOk({
                ...addingRightConfig,
                jobIds: jobTreeKeys,
                rightIds: rightTreeKeys,
              });
            }}
            scrollToFirstError
            style={{
              paddingBlock: 32,
            }}
            labelCol={{
              span: 2,
            }}
            wrapperCol={{
              span: 22,
            }}
          >
            <Form.Item
              label="名称"
              name="name"
              rules={[{ required: true, message: "请输入名称" }]}
            >
              <Input
                value={addingRightConfig.name}
                onChange={(e) => {
                  setAddingRightConfig({
                    ...addingRightConfig,
                    name: e.target.value,
                  });
                }}
                maxLength={100}
                placeholder="请输入"
              />
            </Form.Item>
            <Form.Item
              label="描述"
              name="explain"
              rules={[{ required: true, message: "请输入描述" }]}
            >
              <Input.TextArea
                value={addingRightConfig.explain}
                onChange={(e) => {
                  setAddingRightConfig({
                    ...addingRightConfig,
                    explain: e.target.value,
                  });
                }}
                maxLength={1000}
                rows={4}
                placeholder="请输入"
              />
            </Form.Item>
            <button
              style={{ display: "none" }}
              type="submit"
              ref={submitBtn}
            ></button>
          </Form>
        </div>
        <div style={{ display: "flex" }}>
          <div
            style={{
              flex: 1,
            }}
          >
            <h3 style={{ display: "flex" }}>
              选择职位
              <Checkbox
                style={{ marginLeft: "auto", marginRight: "10px" }}
                onChange={checkJobsAll}
              >
                全选
              </Checkbox>
            </h3>
            <div>
              <Tree
                checkable
                blockNode
                treeData={jobTrees}
                expandedKeys={jobTreeExpandedKeys}
                onExpand={(keys) => setJobTreeExpandedKeys(keys)}
                checkedKeys={jobTreeKeys}
                onCheck={(keys) => setJobTreeKeys(keys)}
                fieldNames={{
                  title: "name",
                  key: "id",
                  children: "childrenDeps",
                }}
              />
            </div>
          </div>
          <div style={{ flex: 1 }}>
            <h3 style={{ display: "flex" }}>
              选择权限
              <Checkbox
                style={{ marginLeft: "auto", marginRight: "10px" }}
                onChange={checkRightsAll}
              >
                全选
              </Checkbox>
            </h3>
            <div>
              <Tree
                checkable
                blockNode
                treeData={rightTrees}
                expandedKeys={rightTreeExpandedKeys}
                onExpand={(keys) => setRightTreeExpandedKeys(keys)}
                checkedKeys={rightTreeKeys}
                onCheck={(keys) => setRightTreeKeys(keys)}
                fieldNames={{ title: "name", key: "id" }}
              />
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
};
export default AddRightConfig;
